﻿namespace Sidvall.Data
{
    public sealed class BusyManager : System.IDisposable
    {
        #region Public Members

        public void Dispose()
        {
            if (this.Provider != null)
            {
                this.Provider.SetIsBusy(this.IsBusy, null, this.Scope);
                this.Provider = null;
            }
        }

        #endregion
        #region Private Members

        private IBusyProvider Provider { get; set; }
        private string Scope { get; set; }
        private bool IsBusy { get; set; }

        #endregion
        #region Constructors

        public BusyManager(IBusyProvider provider) : this(provider, null, null)
        {
        }
        public BusyManager(IBusyProvider provider, string message) : this(provider, message, null)
        {
        }
        public BusyManager(IBusyProvider provider, string message, string scope)
        {
            this.Provider = provider;
            if (this.Provider != null)
            {
                this.IsBusy = this.Provider.IsBusy;
                if (!string.IsNullOrWhiteSpace(scope))
                    this.Scope = scope;
                else
                    this.Scope = System.Guid.NewGuid().ToString();
                if (string.IsNullOrWhiteSpace(message))
                    message = Sidvall.Resources.ResourceKeyManager.Current.IsBusyDefaultMessage;
                this.Provider.SetIsBusy(true, message, this.Scope);
            }
        }

        #endregion
    }
}
